<?php
/**
 * App_Ro
 *
 * @package    App
 * @subpackage App_Ro
 */

/**
 * エントリーリソース
 *
 * @category   BEAR
 * @package    App
 * @subpackage App_Ro
 * @author     $Author: anonymous $ <anonymous@example.com>
 * @version    SVN: Release: $Id:$
 */
class App_Ro_Entry extends App_Ro
{
    /**
     * テーブル名
     *
     * @var string
     */
    protected $_table = App_Ro::TABLE_ENTRY;

    /**
     * コンストラクタ
     */
    public function __construct(array $config)
    {
        parent::__construct($config);
    }

    /**
     * インジェクタ
     */
    public function onInject()
    {
        parent::onInject();
        $this->_queryConfig['pager'] = 1;
        $this->_queryConfig['perPage'] = 5;
        $this->_query = BEAR::dependency('BEAR_Query', $this->_queryConfig, false);
    }

    /**
     * リソース作成
     *
     * @required user_id
     * @required body
     */
    public function onCreate($values)
    {
        $values['created_at'] = _BEAR_DATETIME; //現在時刻
        $result = $this->_query->insert($values);
        if ($this->_query->isError($result)) {
            throw $this->_exception('登録できませんでした', 500);
        }
    }

    /**
     * リソース変更
     *
     * @required id
     */
    public function onUpdate($values)
    {
        $values['created_at'] = _BEAR_DATETIME; //現在時刻
        $where = 'id = ' . $this->_query->quote($values['id'], 'integer');
        $result = $this->_query->update($values, $where);
        return $result;
    }

    /**
     * リソース読み込み
     *
     * <pre>
     * </pre>
     *
     * @required id
     */
    public function onRead($values)
    {
        $sql = "SELECT entries.created_at,
        entries.body,
        entries.reply_user_id,
        users.user_name,
        users.image,
        entries.id as entry_id,
        users.id as user_id,
        entries.deleted_at
        FROM users INNER JOIN entries ON users.id = entries.user_id
        WHERE entries.id = :id";
        $result = $this->_db->queryRow($sql, $values);
        return $result;
    }

    /**
     * リソース削除
     *
     * @required id
     */
    public function onDelete($values)
    {
        $values['deleted_at'] = _BEAR_DATETIME;
        $where = 'id = ' . $this->_query->quote($values['id'], 'integer')
        . ' AND user_id = '. $this->_query->quote($values['user_id'], 'integer');
        $result = $this->_query->update($values, $where);
        return $result;
    }
}